import { defineComponent, ref } from 'vue'
import { addRole, editRole } from '@/api/setting'
import { message, FormInstance } from 'ant-design-vue'

export default defineComponent({
  name: 'ModelCom',
  emits: ['run'],
  setup(props, { emit, expose }) {
    const visible = ref(false)
    const mode = ref('add')
    const formState = ref({
      name: '',
      description: ''
    })
    const formRef = ref<FormInstance>()

    function handleOk() {
      formRef.value?.validateFields().then(async () => {
        let res = {} as any
        if (mode.value === 'add') {
          res = await addRole(formState.value)
        }
        if (mode.value === 'edit') {
          res = await editRole(formState.value)
        }
        message.success(res.message)
        visible.value = false
        emit('run')
      })
    }

    function handlenCancel() {
      // 关闭弹窗
      visible.value = false
    }

    function handlenAfterClose() {
      // 关闭弹窗后
      visible.value = false
      formState.value = {
        name: '',
        description: ''
      }
      formRef.value?.resetFields()
    }

    function handleVisible() {
      visible.value = true
    }

    expose({
      mode,
      formState,
      handleVisible
    })

    return () => (
      <>
        <a-modal
          v-model:visible={visible.value}
          title={mode.value === 'add' ? '添加' : '编辑'}
          onOk={handleOk}
          onCancel={handlenCancel}
          afterClose={handlenAfterClose}
        >
          <a-form
            model={formState.value}
            ref={formRef}
            name="basic"
            label-col={{ span: 6 }}
            wrapper-col={{ span: 16 }}
            autocomplete="off"
          >
            <a-form-item
              label="角色名称"
              name="name"
              rules={[{ required: true, message: '必填' }]}
            >
              <a-input v-model:value={formState.value.name} />
            </a-form-item>
            <a-form-item
              label="角色描述"
              name="description"
              rules={[{ required: true, message: '必填' }]}
            >
              <a-input v-model:value={formState.value.description} />
            </a-form-item>
          </a-form>
        </a-modal>
      </>
    )
  }
})
